package 实现数据结构.算法.链表.单链表;

import 实现数据结构.exception.MyException;
import 实现数据结构.算法.链表.Node;

/**
 * @DESC 单链表示例
 * @Author tzq
 * @Date 2019-08-17 18:29
 * 来自：https://www.cnblogs.com/_popc/p/4025684.html
 **/
public class LinkList {
    Node first; //头结点
    int pos = 0; //节点的位置从0开始（链表无下标概念）

    public LinkList() {
        this.first = null;
    }

    public void addFirstNode(int data) {
        Node node = new Node(data);
        node.next = first;
        first = node;
    }

    public Node removeFirstNode() {
        Node tmp = first;
        first = tmp.next;
        return tmp;
    }

    // 任意位置插入节点
    public void add(int index, int data) {
        if (index > getListLength()) {
            throw new MyException("插入位置越界！");
        }

        Node node = new Node(data);
        Node current = first;
        Node pre = first;
        while (pos != index) {
            pre = current;
            current = current.next;
            pos++;
        }
        node.next = current;
        pre.next = node;
        pos = 0;
    }

    //显示所有节点值
    public void displayAllNode() {
        Node current = first;
        while (null != current) {
            current.display();
            current = current.next;
        }
    }

    //打印链表长度
    public int getListLength() {
        Node curr = first;
        int num = 0;
        while (null != curr) {
            num++;
            curr = curr.next;
        }
        return num;
    }

    //根据位置查找Node
    public Node findByPos(int index) {
        if (index > getListLength()) {
            throw new MyException("查找位置越界，不存在该元素！");
        }
        Node current = first;
        while (pos != index) {
            current = current.next;
            pos++;
        }

        return current;

    }


    public static void main(String[] args) {
        LinkList linkList = new LinkList();
        linkList.addFirstNode(12);
        linkList.addFirstNode(18);
        linkList.addFirstNode(10);
        // 10 18 12

        //1. 打印链表长度
        System.out.println("1.链表长度：" + linkList.getListLength());

        //2.添加元素
//        linkList.add(2, 11);
//        linkList.add(1, 23);
//        linkList.displayAllNode(); // 10 23 18 12

        //3. 查找index=3
        Node byPos = linkList.findByPos(3);
        System.out.println(byPos.data);


    }
}
